# coding=utf-8
import arcpy
import os
import sys
import xlrd  # 需安装xlrd==1.2.0

# 设置默认编码
try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
except NameError:
    pass
#CHECK_FIELDS = ["ZKJC", "ZKMC", "ZKLB_d"]  # 需要同时匹配的三个字段（均为字符串类型）
# 配置参数
excel_path = r"D:\Northwest_Oilfield\ZXLN_FFC.xlsx"
gdb_path = r"D:\ArcGis\DATA\DataExtraction.gdb"
feature_class = "ZXLN_JBXX"
sheet_name = "Sheet1"

# Excel列索引
ORIGINAL_COL = 0  # 待检测字段（原字段名称）
TARGET_COL = 1  # 成果库字段名称
ALIAS_COL = 2  # 字段别名


def read_mapping():
    """读取Excel映射表，返回映射列表和待检测字段集合"""
    try:
        workbook = xlrd.open_workbook(excel_path)
        if sheet_name not in workbook.sheet_names():
            print(u"错误：工作表'%s'不存在" % sheet_name)
            return None, None

        sheet = workbook.sheet_by_name(sheet_name)

        # 获取表头（兼容Unicode处理）
        header = []
        for col_idx in range(sheet.ncols):
            cell = sheet.cell(0, col_idx)
            cell_value = cell.value
            if isinstance(cell_value, unicode):
                cell_value = cell_value.encode('utf-8')
            header.append(str(cell_value).strip())

        # 验证表头
        required = [u"原字段名称", u"成果库字段名称", u"字段别名"]
        if not all(h in header for h in required):
            print(u"错误：表头需包含%s" % str(required))
            return None, None

        mappings = []
        original_fields = set()  # 待检测字段集合

        # 读取数据行（从第2行开始）
        for row_idx in range(1, sheet.nrows):
            row = []
            for col_idx in range(sheet.ncols):
                cell = sheet.cell(row_idx, col_idx)
                cell_value = cell.value

                # 处理不同类型的单元格值
                if isinstance(cell_value, unicode):
                    cell_value = cell_value.encode('utf-8').strip()
                elif isinstance(cell_value, float):
                    # 处理数值类型（如整数被转为浮点数）
                    if cell_value == int(cell_value):
                        cell_value = str(int(cell_value))
                    else:
                        cell_value = str(cell_value)
                else:
                    cell_value = str(cell_value).strip()

                row.append(cell_value)

            # 验证行数据完整性
            if len(row) < 3 or not row[ORIGINAL_COL] or not row[TARGET_COL]:
                print(u"警告：第%d行数据不完整，跳过" % (row_idx + 1))
                continue

            original = row[ORIGINAL_COL]
            target = row[TARGET_COL]
            alias = row[ALIAS_COL]

            mappings.append({"original": original, "target": target, "alias": alias})
            original_fields.add(original.lower())  # 小写存储，避免大小写问题

        print(u"成功读取%d条映射，待检测字段共%d个" % (len(mappings), len(original_fields)))
        return mappings, original_fields

    except Exception as e:
        print(u"读取Excel失败：%s" % str(e))
        return None, None


def get_standard_fields(fc_path, original_fields):
    """获取标准字段（要素类中除待检测字段外的所有字段）"""
    standard_fields = {}  # 键：小写字段名，值：原始信息
    for field in arcpy.ListFields(fc_path):
        field_key = field.name.lower()
        if field_key not in original_fields:  # 排除待检测字段
            standard_fields[field_key] = {
                "name": field.name,
                "type": field.type
            }
    return standard_fields


def is_field_empty(fc_path, field_name):
    """检查字段是否全为空"""
    try:
        total = 0
        non_empty = 0

        with arcpy.da.SearchCursor(fc_path, [field_name]) as cursor:
            for row in cursor:
                total += 1
                val = row[0]

                if val is not None:
                    if isinstance(val, basestring):
                        if val.strip() != "":
                            non_empty += 1
                    else:
                        non_empty += 1

        return total == 0 or non_empty == 0

    except Exception as e:
        print(u"检查字段'%s'空值失败：%s" % (field_name, str(e)))
        return False


def process_fields():
    fc_path = os.path.join(gdb_path, feature_class)
    if not arcpy.Exists(fc_path):
        print(u"错误：要素类'%s'不存在" % fc_path)
        return False

    # 读取映射和待检测字段
    mappings, original_fields = read_mapping()
    if not mappings or not original_fields:
        return False

    # 获取标准字段（非待检测字段）
    standard_fields = get_standard_fields(fc_path, original_fields)
    print(u"标准字段（非待检测字段）共%d个" % len(standard_fields))

    # 创建临时要素类
    temp_gdb = os.path.join(os.path.dirname(gdb_path), "temp.gdb")
    if not arcpy.Exists(temp_gdb):
        arcpy.CreateFileGDB_management(os.path.dirname(temp_gdb), os.path.basename(temp_gdb))
    temp_fc = os.path.join(temp_gdb, "temp_" + feature_class)
    arcpy.CopyFeatures_management(fc_path, temp_fc)
    print(u"创建临时要素类：%s" % temp_fc)

    # 统计变量
    renamed = 0  # 重命名待检测字段为成果库字段
    deleted = 0  # 删除空待检测字段
    retained = 0  # 保留非空待检测字段
    skipped = 0  # 待检测字段不存在
    failed = 0

    # 处理每个待检测字段
    for mapping in mappings:
        original = mapping["original"]
        target = mapping["target"]
        alias = mapping["alias"]
        original_key = original.lower()
        target_key = target.lower()

        # 检查待检测字段是否存在于要素类中
        if original_key not in [f.name.lower() for f in arcpy.ListFields(fc_path)]:
            print(u"警告：待检测字段'%s'不存在于要素类，跳过" % original)
            skipped += 1
            continue

        # 检查成果库字段是否存在于标准字段中
        if target_key in standard_fields:
            # 成果库字段在标准字段中存在
            print(u"成果库字段'%s'已存在于标准字段中，检查待检测字段'%s'是否为空" % (target, original))

            if is_field_empty(fc_path, original):
                # 待检测字段全为空 → 删除
                try:
                    arcpy.DeleteField_management(temp_fc, original)
                    print(u"操作：待检测字段'%s'全为空，已删除" % original)
                    deleted += 1
                except Exception as e:
                    print(u"失败：删除'%s'出错 - %s" % (original, str(e)))
                    failed += 1
            else:
                # 待检测字段非空 → 保留
                print(u"操作：待检测字段'%s'非空，保留该字段" % original)
                retained += 1

        else:
            # 成果库字段不在标准字段中 → 重命名待检测字段
            try:
                # 重命名并设置别名
                arcpy.AlterField_management(
                    temp_fc,
                    field=original,
                    new_field_name=target,
                    new_field_alias=alias
                )
                print(u"操作：待检测字段'%s'重命名为成果库字段'%s'（别名：%s）" % (original, target, alias))
                renamed += 1
            except Exception as e:
                print(u"失败：重命名'%s'为'%s'出错 - %s" % (original, target, str(e)))
                failed += 1

    # 替换原始要素类
    try:
        if arcpy.Exists(fc_path):
            arcpy.Delete_management(fc_path)
        arcpy.CopyFeatures_management(temp_fc, fc_path)
        print(u"已用处理后的临时要素类替换原始要素类")
    except Exception as e:
        print(u"失败：替换原始要素类出错 - %s" % str(e))
        failed += renamed + deleted

    # 清理临时数据
    try:
        arcpy.Delete_management(temp_gdb)
        print(u"清理临时工作空间成功")
    except:
        print(u"警告：临时工作空间未删除，可手动清理：%s" % temp_gdb)

    # 输出统计
    print(u"\n===== 处理结果 =====")
    print(u"重命名待检测字段：%d个" % renamed)
    print(u"删除空待检测字段：%d个" % deleted)
    print(u"保留非空待检测字段：%d个" % retained)
    print(u"跳过不存在的待检测字段：%d个" % skipped)
    print(u"操作失败：%d个" % failed)
    return True


if __name__ == "__main__":
    print(u"===== 开始字段处理 =====")
    result = process_fields()
    print(u"\n===== 处理结束 =====")
    sys.exit(0 if result else 1)